<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { inviteBusinessUrlSaveApi } from '@/api/merchantManagement'
import { InviteBusinessUrlItem, memberCardItem } from '@/api/merchantManagement/types'
import { useValidator } from '@/hooks/web/useValidator'
import { ElMessage } from 'element-plus'

const { required, lengthRange } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<memberCardItem>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
  inviteName: [required(), lengthRange({ min: 0, max: 50 })],
  userCount: [required()],
  remark: [lengthRange({ min: 0, max: 50 })],
  urlValidDay: [required()],
  activeCount: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const createUser = async (data: any) => {
  const param: InviteBusinessUrlItem = {
    inviteName: data.inviteName,
    remark: data.remark,
    userCount: data.userCount,
    urlValidDay: data.urlValidDay,
    activeCount: data.activeCount,
    trialDay: data.trialDay
  }
  const res = await inviteBusinessUrlSaveApi(param)
  return res.code === 200
}

const updateUser = async (data: any) => {
  const param: InviteBusinessUrlItem = {
    inviteName: data.inviteName,
    remark: data.remark,
    userCount: data.userCount,
    urlValidDay: data.urlValidDay,
    activeCount: data.activeCount,
    trialDay: data.trialDay
  }
  const res = await inviteBusinessUrlSaveApi(param)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.activeCount > 99999) {
      ElMessage.error('活动发布次数不能大于99999次')
      return
    }
    if (formData.urlValidDay > 99999) {
      ElMessage.error('链接有效期不能大于99999天')
      return
    }
    if (formData.id) {
      // 修改
      return updateUser(formData)
    } else {
      // 新增
      return createUser(formData)
    }
  }
}

// 重置Form
const reset = async () => {
  const elForm = await getElFormExpose()
  elForm?.resetFields()
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  reset,
  submit,
  setValues
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
